#!/bin/bash
# Recursively prints a package's BlackArch dependencies.
# Offical repo dependencies are not printed.
#
# usage: get-blackarch-deps <package>
#
# Output is as such:
#  <depth> <package>

export LC_ALL=POSIX

basedir=$(realpath "$(dirname "$0")")
cd "$basedir/.."

# I'm leaving the debug prints in there for now.
exec 2> /dev/null

get_blackarch_deps() {
	local pack=$1
	local n=${2:-1}

	# Don't do anything if maximum depth reached or no package passed.
	if [[ $n == 10 || $# == 0 ]] ; then
		echo >&2 "$n base on $pack"
		return
	fi

	unset depends
	unset makedepends
	unset pkgname

	{
	if source "packages/$pack/PKGBUILD" &> /dev/null ; then
		# Don't print the first package.
		if [[ $n != 1 ]] ; then
			echo $n $pack
			echo >&2 $n $pack
		else
			echo >&2 "$n $pack is original"
		fi

		for dep in "${depends[@]}" "${makedepends[@]}" ; do
			echo >&2 $n "($pkgname)" get_blackarch_deps "$(sed 's/\(>\|<\|=\).*//' <<< $dep)" $(( n + 1 ))
			get_blackarch_deps "$(sed 's/\(>\|<\|=\).*//' <<< $dep)" $(( n + 1 ))
		done
	else
		# Don't do anything if the package couldn't be sourced.
		echo >&2 "$n no source for $pack"
	fi
	} | sort -n | sort -k2 -u
}

get_blackarch_deps "$@" | sort -nr
